package util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;

public class GenerateJsModules {

	public static void main(String[] args) throws IOException {

		// System.out.println(new File("").getAbsolutePath());
		BufferedReader br = new BufferedReader(new FileReader("conf/routes"));

		String line = nextLine(br);
		while (line != null) {
			if (line.startsWith("#MODULE")) {
				writeModule(line.split("\\s+"), br);
			}
			line = nextLine(br);
		}
		br.close();
	}

	private static void writeModule(String desc[], BufferedReader br)
			throws IOException {

		BufferedReader br1 = new BufferedReader(new FileReader(
				"private/module-template.js"));
		File f = new File(desc[2] + ".js");
		System.out.println("Creating module " + desc[1] + " in file "
				+ f.getPath());
		PrintWriter pw = new PrintWriter(f);
		String line = br1.readLine();

		while (!line.startsWith("///////")) {
			pw.println(line);
			line = br1.readLine();
		}
		line = nextLine(br);
		while (!line.startsWith("#ENDMODULE")) {
			if (line.startsWith("#SERVICE")) {
				writeService(line.split("\\s+"), br, pw);
			}
			line = nextLine(br);
		}
		line = br1.readLine();
		while (line != null) {
			pw.println(line);
			line = br1.readLine();
		}
		br1.close();
		pw.println("'" + desc[1] + "');");
		pw.close();
		System.out.println("Module " + desc[1] + " created");
	}

	public static String nextLine(BufferedReader br) throws IOException {
		try {
			String line = br.readLine().trim();
			while (line.length() == 0)
				line = br.readLine().trim();
			return line;
		} catch (NullPointerException e) {

			return null;
		}
	}

	private static void writeService(String[] desc, BufferedReader br,
			PrintWriter pw) throws IOException {
		String[] desc1 = nextLine(br).split("\\s+");
		pw.println("service." + desc[1] + "=$resource('" + desc1[1] + "',{},{"
				+ desc[1] + ":{method:'" + desc1[0] + "',isArray:"
				+ (desc[2].equals("array")) + "}})." + desc[1] + ";");
		// pw.println("service." + desc[1] + " = createService('" + desc1[1]
		// + "', '" + desc1[0] + "', '" + desc[2] + "');");

	}

}
